package cn.rengy.tpa.wxmp.component.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tool.http.HttpUtils;
import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.token.AccessToken;

/**
 * 获取预授权码
 * 参考<a href=
 * "https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=209576a955e1861d95876efe59caed2792c212e0&lang=zh_CN">开发文档</a>
 * @author rengy
 * 
 */
public class PreAuthCodeApi {
	private static Logger logger = LoggerFactory.getLogger(PreAuthCodeApi.class);

	/* 获取预授权码 */
	private static final String URL = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=";
	private AccessToken accessToken;
	public PreAuthCodeApi(AccessToken accessToken) {
		this.accessToken = accessToken;
	}
	
	public PreAuthCodeResponse getPreAuthCode(String component_appid) throws WeChatException{
		PreAuthCodeResponse preAuthCodeResponse=null;
		JSONObject postObject = new JSONObject();
		postObject.put("component_appid", component_appid);
		String postData=postObject.toJSONString();
		for(int i=0;i<2;i++){
			String resultStr = HttpUtils.post(URL+accessToken.token(),postData);
			logger.debug("SubscribeMsgResult:{}",resultStr);
			JSONObject jsonObject = JSONObject.parseObject(resultStr);
			int errCode =jsonObject.getIntValue("errcode");
			if(errCode==0){
				String pre_auth_code=jsonObject.getString("pre_auth_code");
				int expires_in=jsonObject.getIntValue("expires_in");
				preAuthCodeResponse=new PreAuthCodeResponse(pre_auth_code,expires_in);
				return preAuthCodeResponse;
			}else if(errCode==40001){
				accessToken.refresh();
			}else{
				String errmsg=jsonObject.getString("errmsg");
				throw new WeChatException(errCode,errmsg);
			}
		}
		return null;
	}
}
